<template>
    <div class="alphabet">
        <div class="item-list" @touchstart.prevent='handleTouchStart' @touchmove='handleTouchMove' @touchend='handleTouchEnd'>
            <div class="item" v-for='item of alphabetList' :key='item' @click='handleLetterClick' :ref='item'>{{item}}</div>
        </div>
    </div>
</template>
<script>
export default {
  name: 'CityAlphabet',
  props: {
    alphabetList: Array
  },
  data () {
    return {
      touchStatus: false,
      startY: 0,
      timer: null
    }
  },
  updated () {
    // 获取字母A距离顶部的距离
    this.startY = this.$refs['A'][0].offsetTop
    console.log(this.startY)
  },
  methods: {
    handleLetterClick (e) {
      // console.log(e.target.innerText)
      const letter = e.target.innerText
      this.$emit('change', letter)
    },
    handleTouchStart () {
      this.touchStatus = true
    },
    handleTouchMove (e) {
      if (this.touchStatus) {
        // 监听滑动事件
        // 获取触摸时的纵坐标
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          const touchY = e.touches[0].clientY - 79
          const index = Math.floor((touchY - this.startY) / 20)
          if (index >= 0 && index <= this.alphabetList.length) {
            const letter = this.alphabetList[index]
            this.$emit('change', letter)
          }
        }, 16)
      }
    },
    handleTouchEnd () {
      this.touchStatus = false
    }
  }
}
</script>
<style lang="stylus" scoped>
@import '~styles/variables.styl'
.item-list
    width:.4rem
    display:flex
    flex-direction :column
    justify-content :center
    position :absolute
    right:0
    top:1.58rem
    bottom:0
    text-align:center
    .item
        line-height:.4rem
        color :$bgColor
</style>
